<template>
    <view class="page">
        <empty tips="非常抱歉，访问不存在" :isLoading="step !== 2"></empty>
        <empty tips="此时此刻需要您登录喔~" :isLoading="step !== 3"></empty>
        <button style="width: 30vw" v-if="step === 3" type="primary" @tap="goLogin()">去登录</button>
        <empty tips="您还没激活邀请码~" :isLoading="step !== 4"></empty>
        <iframe
            :src="iframeSrc"
            style="width: 100vw; height: 100vh"
            allowfullscreen
            sandbox="allow-same-origin allow-scripts allow-forms"
            v-if="step === 1"
        >
            <p>你的浏览器不支持iframe。</p>
        </iframe>
        <u-modal v-model="show" :show-confirm-button="false" content="请使用微信APP扫码打开"></u-modal>
    </view>
</template>

<script>
import ad from '@/utils/bookad.js'
import Empty from '@/components/empty'
import * as API from '../../api/book'
import Hls from '../../static/hls.js'
import { loginWxH5, getWxCode, isSubscribed, getVisitbook } from '@/api/login/index.js'

export default {
    components: {
        Empty
    },
    data() {
        return {
            step: 1,
            hasInfo: true,
            pageId: null,
            component: null,
            info: {},
            code: '',
            show: false,
            openid: '',
            needAuth: false,
            iframeSrc: '',
			timerId: null, // 用于存储定时任务的ID
        }
    },
    onShow() {
        if (this.step === 3) this.getPageInfo()
        this._isSubscribed(this.openid) // 获取扫码关注状态
    },
    onLoad(options) {
        if (this.platform !== 'H5-WEIXIN') {
            this.show = true
            return
        }
        // type int  1.新书、2.旧书
        API.authDetail(options.id, 2).then((res) => {
            this.needAuth = res.data.needAuth
            if (this.needAuth) {
				if (!options?.code) {
                    console.log(555555);
					const time = parseInt(localStorage.getItem('isLogin'))
					if (time < new Date().getTime() || !time) {
						this._removeLocalLogin()
						this.h5Login(options.id)
					} else if (!(options?.code && toptions?.state)) {
						let openId = localStorage.getItem('openid')
						if (openId) {
							this._getWxCode({
								code: '',
								id: options.id,
								type: 2,
								openid: openId
							})
						}
					}
				} else {
                    console.log(4444444);
                    this.getStatisticsEve()
                }
            } else {
                let openId = localStorage.getItem('openid')
                console.log(33333333, openId);
                if (!openId) {
                    this._removeLocalLogin()
                    this.h5Login(options.id)
                } else {
                    this.getStatisticsEve()
                }
            }
        })
    },
    mounted() {
        if (this.$route.query.id) {
            this.pageId = this.$route.query.id
        }
        if (this.$route.query?.code && this.$route.query?.state) {
            this.code = this.$route.query?.code
            this._getWxCode({ code: this.code, id: this.pageId, type: 2 })
        }
        this.getPageInfo()
    },
    methods: {
        goLogin() {
            uni.navigateTo({
                url: '/pages/login/index'
            })
        },
        isSupported() {
            return (
                Hls.isSupported || document.createElement('video').canPlayType('application/vnd.apple.mpegURL') !== ''
            )
        },
        getPageInfo() {
            if (!this.pageId) {
                this.step = 2
                return
            }
            API.oldDetail(this.pageId)
                .then((res) => {
                    this.step = 1
                    this.info = res.data
                    this.iframeSrc = this.info.url
                })
                .catch((e) => {
                    console.log(e)
                    if (e.result.status === 401) {
                        this.step = 3
                    } else if (e.result.data.invalid) {
                        this.step = 4
                    } else {
                        this.step = 2
                    }
                })
        },
        h5Login(id) {
            loginWxH5({ state: id, url: window.location.href }).then((res) => {
                console.log('res: ', res)
                // uni.redirectTo({ url: res.data.url })
                window.location.href = res.data.url
            })
        },
        _getWxCode(params) {
            API.authDetail(params.id, 2).then((pan) => {
                getWxCode(params).then((res) => {
                    console.log('res: ', res)
                    this.openid = res.data.openid
                    if (res.data.openid == null) {
                        this.$navTo(`pages/book/old-book-detail`, { id: params.id, skip: true }, 'redirectTo')
                    }
                    this._doLocalLogin(res.data.openid)
                    if (!pan.data.needAuth) return
                    if (res.data.adUrl) {
                        ad.init({
                            imgSrc: res.data.adUrl,
                            textcolor: res.data.color,
                            imageUrl: res.data.image_url,
                            closeBtn: 1,
                            end: () => {
                                clearInterval(this.timerId)
                                // this.$navTo(`pages/book/old-book-detail`, { id: params.id, skip: true }, 'redirectTo')
                            }
                        })
                        //定时每两秒查看是否关注，已关注就关闭弹窗并取消定时任务
                        if (!this.timerId) {
                            this.timerId = setInterval(() => this._isSubscribed(this.openid), 5000);
                        }
                    }
                })
            })
        },
        getStatisticsEve(){
			let openId = localStorage.getItem('openid')
            console.log(111111, openId);
            console.log(2222222, this.pageId);
			if (openId) {
				getVisitbook({openId: openId, id: this.pageId, type: 2}).then()
			}
        },
        _isSubscribed(openid) {
            if (openid) {
            	isSubscribed({
            		openid,
					bookId: this.pageId,
					type: 2
            	}).then((res) => {
            		if (res.data.subscribed) {
            			layer.close(layer.index);
            			clearInterval(this.timerId)
            		}
            	})
            } else {
            	clearInterval(this.timerId)
            }
        },
		_doLocalLogin(openid) {
			if (openid) {
				localStorage.setItem('isLogin', new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
				localStorage.setItem('openid', openid)					
			}
            console.log(66666666, openid);
            this.getStatisticsEve()
		},
		_removeLocalLogin() {
			localStorage.removeItem('isLogin')
			localStorage.removeItem('openid')
		}
    }
}
</script>
